package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.EventRepository;
import domain.Administrator;
import domain.Event;
import domain.Participant;

@Service
@Transactional
public class EventService {
	
	// Managed repository -----------------------------------------------------
		
		@Autowired
		private EventRepository eventRepository;
		
		@Autowired
		private AdministratorService administratorService;
		
		@Autowired
		private ParticipantService participantService;
		
		// Constructors -----------------------------------------------------------
		
		public EventService(){
			super();
		}
		
		// Simple CRUD methods ----------------------------------------------------
		
		public Event create() {
			Administrator a = administratorService.findByPrincipal();
			Event e = new Event();
			e.setCreationMoment(new Date());
			e.setAdministrator(a);
			//Reference number??
			return e;
		}

		public void save(Event e) {
			Assert.notNull(e);
			Assert.isTrue(e.getAdministrator().equals(administratorService.findByPrincipal()));
			Assert.isTrue(e.getRegistrations().isEmpty());
			eventRepository.save(e);
		}
		
		public void delete(Event e){
			Assert.notNull(e);
			Assert.isTrue(e.getAdministrator().equals(administratorService.findByPrincipal()));
			Assert.isTrue(e.getRegistrations().isEmpty());
			eventRepository.delete(e);
		}
		
		// Other business methods -------------------------------------------------
		
		public Collection<Event> findEventsByAdministrator(){
			Administrator ad = administratorService.findByPrincipal();
			return eventRepository.findEventsByAdministrator(ad.getId());
		}
		
		public Collection<Event> findEventsByParticipant(){
			Participant pa = participantService.findByPrincipal();
			return eventRepository.findEventsByParticipant(pa.getId());
		}
		
		public Collection<Event> findFutureEvents(){
			return eventRepository.findFutureEvents();
		}
		
		public Collection<Event> findOngoingEvents(){
			return eventRepository.findOngoingEvents();
		}
		
		public Collection<Event> findOngoingEventsByAdministrator(){
			return eventRepository.findOngoingEventsByAdministrator();
		}

}
